package com.sync.syncmasterdata.customer.service.impl;


import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import com.sync.syncmasterdata.customer.service.http.HttpAPIServiceForCrmSync;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用服务类
 */
@Service
public class UtilService {

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private HttpAPIServiceForCrmSync httpAPIServiceForCrmSync;

    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 获取 crm地域 字典
     * @return
     */
    public Map<String,JSONObject> getCrmAreaMap(){
        String url=String.format("%s%s", confInfo.getCrmurl(),"new_sites?$select=new_name,new_oa_id,new_adress_code,new_siteid&$filter=new_adress_level eq 1 or new_adress_level eq 2");
        try{
            String responstStr= httpAPIServiceForCrmSync.doGetCrm(url);
            JSONObject jsonObject = new JSONObject(responstStr);
            JSONArray value = new JSONArray(jsonObject.get("value").toString());

            Map<String, JSONObject> siteMap = new HashMap<>();
            for (int i = 0; i < value.length(); i++) {
                JSONObject json = value.getJSONObject(i);
                JSONObject tmp = new JSONObject();
                tmp.put("new_name", json.getString("new_name"));
                tmp.put("new_oa_id", json.get("new_oa_id").toString());
                tmp.put("new_adress_code", json.get("new_adress_code").toString());
                siteMap.put(json.get("new_siteid").toString(), tmp);
            }
            return siteMap;
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 钉钉用服务
     * @return
     * @throws Exception
     */

    public String getToken() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                // 机器人的appkey
                .setAppKey(this.confInfo.getRebotKey())
                // 机器人的appSecret
                .setAppSecret(this.confInfo.getRebotSecret());
        GetAccessTokenResponse rsp = client.getAccessToken(getAccessTokenRequest);
        System.out.println(objectMapper.writeValueAsString(rsp.getBody()));
        String access_token=rsp.getBody().getAccessToken();
        return access_token;
    }

}
